//
//  ForgetPasswordViewController.m
//  bus
//
//  Created by hychen on 2017/4/5.
//  Copyright © 2017年 Hychen. All rights reserved.
//

#import "ForgetPasswordViewController.h"
#import "ForgetPasswordViewModel.h"

static const NSInteger countTime = 300;

@interface ForgetPasswordViewController ()
@property (weak, nonatomic) IBOutlet UITextField *accountTextField;
@property (weak, nonatomic) IBOutlet UITextField *validcodeTextField;
@property (weak, nonatomic) IBOutlet UIButton *validcodeButton;
@property (weak, nonatomic) IBOutlet UIButton *confirmButton;
@property (weak, nonatomic) IBOutlet UITextField *destinTF;
@property (weak, nonatomic) IBOutlet UITextField *destinSureTF;


@property (nonatomic, strong) ForgetPasswordViewModel *forgetVM;
// 倒计时
@property (nonatomic, strong) NSTimer *timer;
// 定时器开启时的date
@property (nonatomic, strong) NSDate *timerDate;
@property (nonatomic, assign) BOOL isChecking;
@end

@implementation ForgetPasswordViewController

#pragma mark - view life circle  viewController生命周期方法
- (void)viewDidLoad {
    [super viewDidLoad];
    [self prepareFunc];
    [self prepareUI];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - custom methods  自定义方法
- (void)prepareFunc{
    [self.navigationItem addSimpleTitleView:@"找回密码"];
}

- (void)prepareUI{
    self.confirmButton.userInteractionEnabled = NO;
    self.validcodeButton.layer.cornerRadius = 14.f;
    self.validcodeButton.layer.borderWidth = 1;
    self.validcodeButton.layer.borderColor = Color_RGB(0, 218, 146).CGColor;
    self.validcodeButton.layer.masksToBounds = YES;
    
    [self.view addTapGestureWithTarget:self action:@selector(tapViewEndEditing:)];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
}

- (void)willEnterForeground:(NSNotification *)notify{
    if (self.isChecking) {
        [self startTimer];
    }
}
- (void)textFieldObserver{
    if (self.accountTextField.text.length>0 && self.validcodeTextField.text.length>0) {
        self.confirmButton.userInteractionEnabled = YES;
    }else{
        self.confirmButton.userInteractionEnabled = NO;
    }
}
#pragma mark - 按钮响应
- (void)tapViewEndEditing:(UITapGestureRecognizer *)tap{
    [self.view endEditing:YES];
}

- (IBAction)validcodeButtonClick:(UIButton *)sender {
    if (self.accountTextField.text.length < 1) {
        Show_Msg_Error(@"请填写手机号码")
        return;
    }
    if (![CheckUtility checkForNumber:self.accountTextField.text] || (self.accountTextField.text.length<5 || self.accountTextField.text.length>15)) {
        Show_Msg_Error(@"手机号码错误")
        return;
    }
    WeakSelf_bb
    [self.forgetVM requestValidCodeWithPhone:self.accountTextField.text success:^(id object) {
        [weakSelf startTimer];
        [weakSelf.validcodeTextField becomeFirstResponder];
    } failure:^(NSString *code, NSString *msg) {
        
    }];
}

- (IBAction)confirmButtonClick:(UIButton *)sender {
    [self.view endEditing:YES];
    
    if (self.accountTextField.text.length < 1) {
        Show_Msg_Error(@"请输入手机号码")
        return;
    }
    else if (self.validcodeTextField.text.length < 1) {
        Show_Msg_Error(@"请输入验证码")
        return;
    }
    else if (self.destinTF.text.length < 1) {
        Show_Msg_Error(@"请输入新设密码")
        return;
    }
    else if (self.destinSureTF.text.length < 1) {
        Show_Msg_Error(@"请输入确认密码")
        return;
    }
    else if (self.destinTF.text.length < 6 && self.destinTF.text.length > 0) {
        Show_Msg_Error(@"新设密码不应小于6位")
        return;
    }
    else if (self.destinSureTF.text.length < 6 && self.destinSureTF.text.length > 0) {
        Show_Msg_Error(@"确认密码不应小于6位")
        return;
    }
    else if (self.validcodeTextField.text.length < 1) {
        Show_Msg_Error(@"请输入验证码")
        return;
    }
    
    //网络请求
    WeakSelf_bb
    [self.forgetVM requestForgetPasswordDataWithParams:@[API_App_User_FindPwd,self.accountTextField.text,self.validcodeTextField.text,[self.destinTF.text MD5_lib]] success:^(id object) {
        Show_Msg_Success(@"修改密码成功")
        if (weakSelf.successRequestNewPwdBlock) {
            weakSelf.successRequestNewPwdBlock(weakSelf.accountTextField.text);
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        });
        
    } failure:^(NSString *code, NSString *msg) {
        Show_Msg_Error(msg)
    }];

}

#pragma mark - 事件响应
- (IBAction)accountTextFieldEditingChange:(UITextField *)sender {
    [self textFieldObserver];
}

- (IBAction)validcodeTextFieldEditingChange:(UITextField *)sender {
    [self textFieldObserver];
}

- (IBAction)destinPwdOpenClick:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.destinTF.secureTextEntry = !sender.selected;
}

- (IBAction)destinSurePwdOpenClick:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.destinSureTF.secureTextEntry = !sender.selected;
}

#pragma mark - 验证码倒计时
#pragma mark - 倒计开始
-(void)startTimer
{
    [self.timer invalidate];
    self.timer = nil;
    if (!self.timerDate) {
        self.timerDate = [NSDate date];
    }
    NSTimeInterval timerInterval = [self.timerDate timeIntervalSinceNow];
    NSInteger timeLeft = countTime + round(timerInterval);
    if (timeLeft <= 0) {
        self.isChecking = NO;
        return;
    }
    self.isChecking = YES;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(refreshCheckCodeText:) userInfo:self.timerDate repeats:YES];
    self.validcodeButton.enabled = NO;
}
#pragma mark - 倒计时结束
-(void)timeIsUp
{
    self.isChecking = NO;
    [self.timer invalidate];
    self.timer = nil;
    self.timerDate = nil;
    [self.validcodeButton setTitle:@"验证码" forState:UIControlStateNormal];
    self.validcodeButton.titleLabel.text = @"验证码";
    self.validcodeButton.enabled = YES;
}
#pragma mark - 刷新倒计时文本
-(void)refreshCheckCodeText:(NSTimer *)timer
{
    NSDate *dateRef = timer.userInfo;
    NSTimeInterval timerInterval = [dateRef timeIntervalSinceNow];
    NSInteger timeLeft = countTime + round(timerInterval);
    if (timeLeft <= 0) {
        [self timeIsUp];
        return;
    }
    NSString *secondTitle = [NSString stringWithFormat:@"(%ld)秒",(long)timeLeft];
    //解决闪烁问题
    self.validcodeButton.titleLabel.text = secondTitle;
    //倒计时时不能点击
    [self.validcodeButton setTitle:secondTitle forState:UIControlStateNormal];
    
}


#pragma mark - sources and delegates 代理、协议方法

#pragma mark - getters
- (ForgetPasswordViewModel *)forgetVM{
    if (!_forgetVM) {
        _forgetVM = [[ForgetPasswordViewModel alloc] init];
    }
    return _forgetVM;
}
#pragma mark - setters



@end
